<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <h2>原始图片</h2>
        <img id="originalImage" src="../../../tool/img/test.jpg" alt="原始图片">
    </div>
    <div>
        <h2>带水印的图片</h2>
        <canvas id="watermarkCanvas"></canvas>
    </div>

    <script>
        function addWatermarkToImage(imageId, canvasId, watermarkText) {
            const image = document.getElementById(imageId);
            const canvas = document.getElementById(canvasId);
            const ctx = canvas.getContext('2d');

            // 等图片加载完成后绘制
            image.onload = function () {
                // 设置 canvas 尺寸为图片尺寸
                canvas.width = image.width;
                canvas.height = image.height;

                // 绘制图片到 canvas
                ctx.drawImage(image, 0, 0);

                // 设置水印样式
                const fontSize = Math.min(image.width, image.height) / 20; // 动态调整字体大小
                ctx.font = `${fontSize}px Arial`;
                ctx.fillStyle = 'rgba(184, 184, 184, 0.6)';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';

                // 旋转角度
                const angle = -Math.PI / 4;

                // 绘制水印
                ctx.save();
                ctx.translate(image.width / 2, image.height / 2); // 将原点移至画布中心
                ctx.rotate(angle); // 旋转画布

                const stepX = fontSize * 6; // 水平方向间距
                const stepY = fontSize * 6; // 垂直方向间距

                for (let y = -image.height; y < image.height * 2; y += stepY) {
                    for (let x = -image.width; x < image.width * 2; x += stepX) {
                        ctx.fillText(watermarkText, x, y);
                    }
                }
                ctx.restore();
            };
        }

        // 使用示例
        addWatermarkToImage('originalImage', 'watermarkCanvas', '水印文字');
    </script>
</body>

</html>